<?php

/**
 * URI分析类
 * 
 * @package    01CMS
 * @subpackage system
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class Uri
{
	private $className;
	private $methodName;
	private $param;
	private $uriString;

	function __construct ()
	{
		if (! empty($_SERVER['PATH_INFO']))
		{
			$this->uriString = trim($_SERVER['PATH_INFO'], '/');
			$urlSuffix = $GLOBALS['Load']->config['urlSuffix'];
			if (! empty($urlSuffix))
			{
				$this->uriString = preg_replace($urlSuffix . '$', '', $this->uriString);
			}
			$uriArr = explode("/", $this->uriString);
			$segments = array();
			foreach ($uriArr as $val)
			{
				$val = trim($this->filterSegment($val));
				if ($val != '')
				{
					$segments[] = $val;
				}
			}
			$this->className = empty($segments[0]) ? '' : ucfirst($segments[0]);
			$this->methodName = empty($segments[1]) ? '' : $segments[1];
			$this->param = isset($segments[2]) ? array_slice($segments, 2) : array();
		}
		else if (! empty($_GET['c_']))
		{
			$this->className = isset($_GET['c_']) ? $this->filterSegment($_GET['c_']) : '';
			$this->methodName = isset($_GET['m_']) ? $this->filterSegment($_GET['m_']) : '';
			$count = count($_GET);
			for ($i = 1; $i < $count; $i ++)
			{
				if (isset($_GET['p' . $i . '_']))
				{
					$this->param[] = $this->filterSegment($_GET['p' . $i . '_']);
				}
				else
				{
					break;
				}
			}
		}
	}

	private function filterSegment ($str)
	{
		if (substr($str, 0, 1) == '_')
		{
			showError('Bad Request');
		}
		$bad = array('$' , '(' , ')' , '%28' , '%29');
		$good = array('&#36;' , '&#40;' , '&#41;' , '&#40;' , '&#41;');
		$str = str_replace($bad, $good, $str);
		$str = slashQuotes($str);
		return $str;
	}

	public function getClassName ()
	{
		return empty($this->className) ? 'index' : strtolower($this->className);
	}

	public function getMethodName ()
	{
		return empty($this->methodName) ? 'index' : $this->methodName;
	}

	public function getParam ()
	{
		return $this->param;
	}

	public function getUriString ()
	{
		return $this->uriString;
	}
}